﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Net;

namespace CoderJoe.Net
{
    public class NetworkConnectivity
    {
        public static bool CanConnectToWebsite(Uri url, TimeSpan timeout)
        {
            try
            {
                WebHelper.GetHeaders(url, timeout);
                return true;
            }
            catch (WebException wex)
            {
                switch (wex.Status)
                {
                    case WebExceptionStatus.ProtocolError:
                        break;
                    default:
                        throw wex;
                }
            }

            return false;
        }

        public static bool IsInternetConnected()
        {
            InternetConnectionState state = GetInternetConnectionState();
            if ((state & InternetConnectionState.Offline) != InternetConnectionState.Offline)
                return true;

            return false;
        }

        public static InternetConnectionState GetInternetConnectionState()
        {
            InternetConnectionState state = InternetConnectionState.None;

            if (InternetGetConnectedState(ref state, 0) == false)
            {
                int lastError = Marshal.GetLastWin32Error();
                if(lastError > 0)
                    throw new Win32Exception(lastError);
            }

            return state;
        }

        [DllImport("wininet.dll", CharSet=CharSet.Auto, SetLastError=true)]
        private extern static bool InternetGetConnectedState(ref InternetConnectionState state, int reserved);

        private enum InternetConnectionState
        {
            None = 0x0,
            Modem = 0x1,
            Lan = 0x2,
            Proxy = 0x4,
            RasInstalled = 0x10,
            Offline = 0x20,
            Configured = 0x40,
        }
    }
}
